import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_reader/config/user_manager.dart';
import 'package:flutter_reader/res/colors.dart';
import 'package:flutter_reader/ui/book_city/book_city_page.dart';
import 'package:flutter_reader/ui/bookshelf/bookshelf_page.dart';
import 'package:flutter_reader/ui/me/me_page.dart';
import 'package:flutter_reader/utils/event_bus.dart';

const String EventToggleTabBarIndex = 'EventToggleTabBarIndex';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _tabIndex = 1;
  List<Image> _tabImages = [
    Image.asset('img/tab_bookshelf_n.png'),
    Image.asset('img/tab_bookstore_n.png'),
    Image.asset('img/tab_me_n.png'),
  ];
  List<Image> _tabSelectedImages = [
    Image.asset('img/tab_bookshelf_p.png'),
    Image.asset('img/tab_bookstore_p.png'),
    Image.asset('img/tab_me_p.png'),
  ];

  @override
  void initState() {
    super.initState();

    EventBus.instance.on(EventUserLogin, (arg) {
      setState(() {});
    });

    EventBus.instance.on(EventUserLogout, (arg) {
      setState(() {});
    });

    EventBus.instance.on(EventToggleTabBarIndex, (index) {
      setState(() {
        _tabIndex = index;
      });
    });
  }

  @override
  void dispose() {
    EventBus.instance.off(EventUserLogin);
    EventBus.instance.off(EventUserLogout);
    EventBus.instance.off(EventToggleTabBarIndex);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        children: [
          BookshelfPage(),
          BookCityPage(),
          MePage(),
        ],
        index: _tabIndex,
      ),
      bottomNavigationBar: CupertinoTabBar(
        backgroundColor: Colors.white,
        activeColor: MyColors.primary,
        items: [
          BottomNavigationBarItem(icon: getTabIcon(0), label: '书架'),
          BottomNavigationBarItem(icon: getTabIcon(1), label: '书城'),
          BottomNavigationBarItem(icon: getTabIcon(2), label: '我的'),
        ],
        currentIndex: _tabIndex,
        onTap: (index) {
          setState(() {
            _tabIndex = index;
          });
        },
      ),
    );
  }

  Image getTabIcon(int index) {
    if (index == _tabIndex) {
      return _tabSelectedImages[index];
    } else {
      return _tabImages[index];
    }
  }
}
